/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package nvPlaces;

import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
import org.nViron.nvCommon.nvPosition;
import org.nViron.nvData.nvDataEntity;

/**
 *
 * @author Roland
 */
public class nvBasicClusterer implements nvClusterer {

    private float minDistanceForStacking;

    public nvBasicClusterer() {
        minDistanceForStacking = 25.0f;
    }

    public float getMinDistanceForStacking() {
        return minDistanceForStacking;
    }

    public void setMinDistanceForStacking(float minDistanceForStacking) {
        this.minDistanceForStacking = minDistanceForStacking;
    }

    @Override
    public nvPosition getCenter(Vector entities) {
        // simple geometeric implementation
        nvPosition center = new nvPosition();
        for (Enumeration e = entities.elements() ; e.hasMoreElements() ;) {
            nvDataEntity entity = (nvDataEntity)e.nextElement();
            center.incLongitude(entity.getPosition().getLongitude());
            center.incLatitude(entity.getPosition().getLatitude());
            center.incAltitude(entity.getPosition().getAltitude());
        }
        center.mulLongitude(1.0/(double)entities.size());
        center.mulLatitude(1.0/(double)entities.size());
        center.mulAltitude(1.0f/(float)entities.size());

        return center;
    }

    @Override
    public nvPlace findPlaceForEntity(Hashtable places, nvDataEntity entity) {
        nvPlace foundPlace = null;
        double minDist = 10000000.0;
        for (Enumeration e = places.keys(); e.hasMoreElements(); ) {
            Object key = e.nextElement();
            nvPlace place = (nvPlace)places.get(key);
            double dist = place.getCenter().getDistance2d(entity.getPosition());
            System.out.println("Distance: " + dist);
            if (dist < getMinDistanceForStacking()) {
                if (foundPlace == null || (foundPlace != null && dist < minDist)) {
                    if (foundPlace != null) {
                        // TODO check if we get here, cause this means, that we have potentially overlapping places (don't know yet if this is good or bad)
                    }
                    minDist = dist;
                    foundPlace = place;
                }
            }
        }
        return foundPlace;
    }

    @Override
    public void balancePlaces(Hashtable places) {
        // TODO do some balancing?
    }

    @Override
    public boolean keepCenter(nvPosition center, nvPosition newCenter) {
        float threshold = getMinDistanceForStacking() / 10.0f;
        return center.getDistance2d(newCenter) < threshold;
    }

}
